<template>
  <div class="page-common-layout black-hole-qiankun-container">
    <div class="graphic-ant-tabs-nav">
      <div class="tabs-nav-container">
        <div
          class="tab-nav-item "
          :class="dataType == item.dataType && 'active'"
          v-for="(item, index) in tabNavSource"
          :key="index"
          @click="checkDataType(item)"
        >
          {{ item.name }}
        </div>
      </div>
      <div class="button-container">
        <!-- <a-select
          v-if="projectSource.length > 0"
          v-model="projectId"
          style="width: 400px"
          placeholder="请选择项目"
          @change="handleChange"
        >
          <a-select-option
            :value="item.foreignUuid"
            v-for="(item, index) in projectSource"
            :key="index"
            :disabled="!item.foreignUuid"
          >
            <span :title="item.proName">{{ item.proName }}</span>
          </a-select-option>
        </a-select> -->
        <a-tree-select
          v-if="false"
          style="width: 400px"
          v-model="projectId"
          treeNodeFilterProp="title"
          show-search
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          placeholder="请选择"
          searchPlaceholder="请输入"
          tree-default-expand-all
          :replaceFields="{
            children: 'child',
            title: 'orgName',
            key: 'id',
            value: 'foreignUuid',
          }"
          :tree-data="projectSource"
          @change="handleChange"
        >
        </a-tree-select>
        <a-button
          type="primary"
          icon="cloud-upload"
          @click="openSubModal('uploadListVisible')"
        >
          上传列表
        </a-button>
        <a-button
          type="primary"
          icon="bars"
          @click="openSubModal('transformListVisible')"
        >
          转换队列
        </a-button>
      </div>
    </div>
    <div id="app-for-graphic"></div>
  </div>
  <!--  -->
</template>
<script>
import Vue from "vue";
import { mapGetters } from "vuex";
import { SCRIPT_TYPE_REGEX } from "@/blackHole/blackholeAsset";
import { loadMicroApp } from "qiankun";
import { axios } from "@/utils/request";
import { canvasHolder } from "@/blackHoleTools/CanvasHolder";
import {
  restEngine,
  initialSDKModule,
  releaseEngine,
} from "@/blackHoleTools/Engine";
export default {
  data() {
    return {
      projectId: undefined,
      bimController: null,
      loading: false,
      projectSource: [],
      dataType: "Bim",
      tabNavSource: [
        {
          name: "模型数据",
          dataType: "Bim",
        },
        {
          name: "遥感数据",
          dataType: "Rs",
        },
        {
          name: "WMTS地图服务",
          dataType: "Wmts",
        },
        {
          name: "倾斜摄影",
          dataType: "Osgb",
        },
        {
          name: "360全景图",
          dataType: "Panorama",
        },
        {
          name: "点云",
          dataType: "PointCloud",
        },
      ],
    };
  },
  computed: {
    ...mapGetters([
      "blackHoleAssetsPreFetch",
      "blackHoleRESystemCreated",
      "currentProject",
    ]),
    routerPid() {
      let { projectId } = this.$route.params;
      return {
        projectId,
      };
    },
  },
  watch: {
    //系统引擎创建完成 && 公共资源加载完成
    // RESystemRenderReady: {
    //   handler(val) {
    //     if (val == true) {
    //       let { dataType } = this.$route.query;
    //       this.dataType = dataType;
    //       this.getBlackHoleToken().then((res) => {
    //         let { blackToken } = res;
    //         this.loadMicroApp(blackToken);
    //       });
    //     }
    //   },
    //   immediate: true,
    // },

    blackHoleAssetsPreFetch: {
      handler(val) {
        this.$nextTick((_) => {
          if (val) {
            initialSDKModule();
          }
        });
      },
      immediate: true,
    },

    blackHoleRESystemCreated: {
      handler(val) {
        if (val) {
          this.$nextTick((_) => {
            let { dataType } = this.$route.query;
            this.dataType = dataType;
            this.getBlackHoleToken().then((res) => {
              let { blackToken } = res;
              this.loadMicroApp(blackToken);
            });
          });
        }
      },
      immediate: true,
    },

    $route: {
      handler(val) {
        let { projectId } = val.params;
        this.projectId = projectId === "$$INIT" ? undefined : projectId;
      },
      immediate: true,
    },

    routerPid: {
      handler() {
        let { foreignUuid } = this.currentProject ?? {};
        let { projectId } = this.$route.params;
        if (foreignUuid && projectId === "$$INIT") {
          setTimeout(() => {
            this.$router
              .push({
                path: `/singleProject/dataManage/${foreignUuid}/projectName?dataType=Bim`,
              })
              .then((v) => {
                this.getBlackHoleToken().then((res) => {
                  let { blackToken } = res;
                  this.loadMicroApp(blackToken);
                });
              });
          }, 500);
        }
      },
      immediate: true,
    },
  },
  mounted() {
    let { foreignUuid } = this.currentProject ?? {};
    if (foreignUuid) {
      setTimeout(() => {
        this.$router.push({
          path: `/singleProject/dataManage/${foreignUuid}/projectName?dataType=Bim`,
        });
      }, 500);
    }
  },
  methods: {
    //查询项目列表
    getProjectList() {
      this.loading = true;
      return new Promise((resolve, reject) => {
        axios
          .get(
            `/mdata/sysProject/getProListTreeByQX`,
            {},
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            let list = res?.data ?? [];
            this.dealTreeDta(list);
            this.projectSource = list;
            resolve();
          })
          .catch((_) => {
            this.projectSource = [];
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },

    //
    dealTreeDta(oriData = []) {
      _deal(oriData);
      function _deal(data) {
        data.forEach((v) => {
          let { child, foreignUuid } = v;
          if (!foreignUuid) {
            v.disabled = true;
          } else {
            v.disabled = false;
          }
          if (child && child.length > 0) {
            _deal(child);
          }
        });
      }
    },

    // //查询项目列表
    // getProjectList() {
    //   this.loading = true;
    //   return new Promise((resolve, reject) => {
    //     this.$get("/mdata/sysProject/getProListByQX")
    //       .then((res) => {
    //         this.projectSource = res?.data ?? [];
    //         resolve();
    //       })
    //       .catch((_) => {
    //         this.projectSource = [];
    //         reject();
    //       })
    //       .finally((_) => {
    //         this.loading = false;
    //       });
    //   });
    // },

    //刷新黑洞token
    getBlackHoleToken() {
      return new Promise((resolve, reject) => {
        axios
          .post(
            `/system/blackHoleTokenRefresh`,
            {},
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            resolve(res);
          })
          .catch((_) => {
            resolve(null);
          });
      });
    },

    //【挂载 & 卸载】 微应用
    loadMicroApp(blackToken) {
      setTimeout((_) => {
        this.$nextTick((_) => {
          //如果应用已经挂在-卸载后重新挂载
          if (window.blackHoleMicroApp) {
            let { blackHoleMicroApp } = window;
            let { unmount } = blackHoleMicroApp;
            //卸载
            unmount();
            //监听卸载完成
            blackHoleMicroApp.unmountPromise.then((res) => {
              setTimeout(() => {
                this.loadblackHoleApp(blackToken);
              }, 500);
            });
            return;
          } else {
            setTimeout(() => {
              this.loadblackHoleApp(blackToken);
            }, 500);
          }
        });
      }, 600);
    },

    //监听项目切换
    handleChange(ev) {
      if (!ev) {
        return;
      }
      if (window.blackHoleMicroApp) {
        let { blackHoleMicroApp } = window;
        let { unmount } = blackHoleMicroApp;
        //卸载
        unmount();
        //监听卸载完成
        blackHoleMicroApp.unmountPromise.then((res) => {
          setTimeout(() => {
            this.$router
              .push({
                path: `/singleProject/dataManage/${ev}/projectName?dataType=${this.dataType}`,
              })
              .then((v) => {
                this.loadMicroApp();
              });
          }, 500);
        });
        return;
      } else {
        // this.$router
        //   .push({
        //     path: `/singleProject/dataManage/${ev}/projectName?dataType=${this.dataType}`,
        //   })
        //   .then((v) => {
        //     this.loadMicroApp();
        //   });
      }
    },

    //qiankun
    loadblackHoleApp(blackToken) {
      let token = Vue.ls.get("Black-Token");
      setTimeout((_) => {
        window.blackHoleMicroApp = loadMicroApp(
          {
            name: "blackhole",
            entry: `/blackhole/index.html`,
            container: "#app-for-graphic",
            props: {
              getToken: () => `bearer ${blackToken || token}`,
              onLoadMainSce: () => {
                restEngine();
              },
              onUnloadMainSce: () => {
                console.log("onUnloadMainSce");
                //   clearCacheModelInfo()
              },
              getControllerInstance: (controller) => {
                this.bimController = controller;
              },
            },
          },
          {
            sandbox: true,
            getTemplate: (tpl) => {
              //主题色
              let valObj = window.getComputedStyle(document.body);
              let color = valObj.getPropertyValue("--antd-wave-shadow-color");
              // 过滤掉之前已经加载过的脚本
              let newHtmlString = tpl.replace(SCRIPT_TYPE_REGEX, "");
              const headPosi = newHtmlString.indexOf("<head>") + 6;
              // 插入补丁css
              const patchCss = `<style>:root body[theme-mode=light]{--primary-color:${color}!important} .icon-column:before{content:''!important}  .dialog-container{z-index:999!important;} #__qiankun_microapp_wrapper_for_blackhole__,#__qiankun_microapp_wrapper_for_blackhole_1__,.single-container {height:100%!important} .blackhole-height{height:100%!important} .data-manage-box{padding:0 0 10px 0!important;} .scene-list{margin:0!important;} .single-scene-box {height: 100% !important;} .scene-box {height: 100% !important; }.data-manage-box{height: 100%;width: 100% !important;}.scene-list{width: calc(100% - 40px)!important;}.convert-progress-box{height: 20px !important;}.scene-edit-box{height: 100%!important;}</style>`;
              newHtmlString =
                newHtmlString.slice(0, headPosi) +
                patchCss +
                newHtmlString.slice(headPosi);
              return newHtmlString;
            },
          }
        );
      }, 100);
    },

    checkDataType(item) {
      let { dataType } = item;
      this.dataType = dataType;
      let { projectId } = this;
      this.$router.push({
        path: `/singleProject/dataManage/${projectId}/projectName?dataType=${dataType}`,
      });
    },

    openSubModal(key) {
      let { bimController } = this;
      if (bimController) {
        bimController?.[key]();
      }
    },
  },
  beforeDestroy() {
    canvasHolder.moveCanvasToBody();
    if (window.blackHoleMicroApp) {
      try {
        let { blackHoleMicroApp } = window;
        let { unmount } = blackHoleMicroApp;
        //卸载
        unmount();
      } catch (error) {}
    }
  },
};
</script>
<style lang="less" scoped>
.black-hole-qiankun-container {
  display: flex;
  flex-direction: column;
  .graphic-ant-tabs-nav {
    flex-shrink: 0;
    background-color: #fff;
    padding: 0 20px;
    border-radius: 5px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    .tabs-nav-container {
      display: flex;
      font-size: 14px;
      .tab-nav-item {
        margin: 0 0 0 32px;
        &:first-child {
          margin-left: 0;
        }
        cursor: pointer;
        height: 44px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-bottom: 2px solid #fff;
        &.active {
          color: var(--antd-wave-shadow-color);
          border-bottom: 2px solid var(--antd-wave-shadow-color);
        }
      }
    }
    .button-container {
      button {
        margin-left: 10px;
        &:first-child {
          //   margin-right: 20px;
        }
      }
    }
  }
  #app-for-graphic {
    overflow: hidden;
    display: block;
    flex: 1;
  }
}
</style>
